import axios from 'axios'
import type {
  LoginForm,
  LoginResponse,
  User,
  ProxyConfig,
  ProxyForm,
  AccessStats,
  TrafficData,
  ProxyUsageData,
  AccessLog,
  LogQuery,
  SystemSettings,
  ChangePasswordForm,
  ApiResponse,
  PaginatedResponse
} from '../types'
import { MockApi } from '../mock/api'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 是否使用Mock数据
const USE_MOCK = true

// 认证相关API
export const authApi = {
  // 登录
  login: async (form: LoginForm): Promise<ApiResponse<LoginResponse>> => {
    if (USE_MOCK) {
      return MockApi.login(form.username, form.password)
    }
    return api.post('/auth/login', form)
  },

  // 获取用户信息
  getUserInfo: async (): Promise<ApiResponse<User>> => {
    if (USE_MOCK) {
      return MockApi.getUserInfo()
    }
    return api.get('/auth/user')
  },

  // 修改密码
  changePassword: async (form: ChangePasswordForm): Promise<ApiResponse<void>> => {
    if (USE_MOCK) {
      return MockApi.changePassword(form.oldPassword, form.newPassword)
    }
    return api.post('/auth/change-password', form)
  },

  // 登出
  logout: async (): Promise<void> => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
}

// 代理管理API
export const proxyApi = {
  // 获取代理列表
  getProxies: async (): Promise<ApiResponse<ProxyConfig[]>> => {
    if (USE_MOCK) {
      return MockApi.getProxies()
    }
    return api.get('/proxies')
  },

  // 创建代理
  createProxy: async (proxy: ProxyForm): Promise<ApiResponse<ProxyConfig>> => {
    if (USE_MOCK) {
      return MockApi.createProxy(proxy)
    }
    return api.post('/proxies', proxy)
  },

  // 更新代理
  updateProxy: async (id: number, proxy: Partial<ProxyForm>): Promise<ApiResponse<ProxyConfig>> => {
    if (USE_MOCK) {
      return MockApi.updateProxy(id, proxy)
    }
    return api.put(`/proxies/${id}`, proxy)
  },

  // 删除代理
  deleteProxy: async (id: number): Promise<ApiResponse<void>> => {
    if (USE_MOCK) {
      return MockApi.deleteProxy(id)
    }
    return api.delete(`/proxies/${id}`)
  },

  // 启用/禁用代理
  toggleProxy: async (id: number, isActive: boolean): Promise<ApiResponse<ProxyConfig>> => {
    if (USE_MOCK) {
      return MockApi.updateProxy(id, { isActive })
    }
    return api.patch(`/proxies/${id}/toggle`, { isActive })
  }
}

// 统计数据API
export const statsApi = {
  // 获取访问统计
  getAccessStats: async (): Promise<ApiResponse<AccessStats>> => {
    if (USE_MOCK) {
      return MockApi.getAccessStats()
    }
    return api.get('/stats/access')
  },

  // 获取流量数据
  getTrafficData: async (days: number = 7): Promise<ApiResponse<TrafficData[]>> => {
    if (USE_MOCK) {
      return MockApi.getTrafficData(days)
    }
    return api.get(`/stats/traffic?days=${days}`)
  },

  // 获取代理使用情况
  getProxyUsage: async (): Promise<ApiResponse<ProxyUsageData[]>> => {
    if (USE_MOCK) {
      return MockApi.getProxyUsage()
    }
    return api.get('/stats/proxy-usage')
  }
}

// 日志API
export const logApi = {
  // 获取访问日志
  getAccessLogs: async (query: LogQuery): Promise<ApiResponse<PaginatedResponse<AccessLog>>> => {
    if (USE_MOCK) {
      return MockApi.getAccessLogs(query)
    }
    return api.get('/logs/access', { params: query })
  }
}

// 系统设置API
export const settingsApi = {
  // 获取系统设置
  getSettings: async (): Promise<ApiResponse<SystemSettings>> => {
    if (USE_MOCK) {
      return MockApi.getSystemSettings()
    }
    return api.get('/settings')
  },

  // 更新系统设置
  updateSettings: async (settings: Partial<SystemSettings>): Promise<ApiResponse<SystemSettings>> => {
    if (USE_MOCK) {
      return MockApi.updateSystemSettings(settings)
    }
    return api.put('/settings', settings)
  }
}